import WebGl from '@/modules/three';
import Calc from '@/modules/calc';
import Particle from '../particleBase';
// import fontJson from 'three/examples/fonts/helvetiker_regular.typeface.json'
const fontJson = require('three/examples/fonts/helvetiker_regular.typeface.json');

const { Three, TWEEN, dat, Stats, OrbitControls } = WebGl;

class WebGlControl {
  private container: any;
  private camera: any;
  private scene: any;
  private renderer: any;
  private stats: any;
  private animateFrame: any;
  private tween: any;
  private controls: any;

  private particleGroup: any;
  private Geometrys: {
    sphereGeometry?: any;
  } = {}; //保存所有Geometry，方便统一销毁
  private Materials: {} = {}; //保存所有Material，方便统一销毁
  private particleSystem: any;
  private particles: any[] = [];

  private GuiInit: any = null;
  private guiData: any = {
    x: 0.005,
    color: '#000000',
    autoRotate: true,
  };

  public init = (id: string) => {
    // if(this.scene) {return}
    this.container = document.getElementById(id);
    let width = this.container.clientWidth,
      height = this.container.clientHeight;

    this.scene = new Three.Scene();

    this.camera = new Three.PerspectiveCamera(
      100,
      width / height,
      0.0001,
      10000,
    );
    // this.camera = new THREE.PerspectiveCamera(100, 0, 0.0001, 10000);
    this.camera.position.x = 0;
    this.camera.position.y = 0;
    this.camera.position.z = 30;
    this.camera.lookAt(this.scene.position);

    this.renderer = new Three.WebGLRenderer();
    // this.renderer.setClearColor( 0xffffff );
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(width, height);
    this.container.appendChild(this.renderer.domElement);

    this.controls = new OrbitControls(this.camera, this.renderer.domElement);

    this.setupTime();

    this.addThings();
    this.addLight(); //+光源
    this.animate(); //开始动
    this.initStats();

    this.initGui();
  };
  public destroy = () => {
    this.toggleGui(0);
    Object.values(this.Geometrys).forEach((e) => {
      e.dispose();
    });
    Object.values(this.Materials).forEach((e) => {
      e.dispose();
    });
    this.particleGroup = null;
    this.scene.clear();
    this.renderer.dispose();
    this.renderer.forceContextLoss();
    this.camera = null;
    this.scene = null;
    this.renderer = null;
    this.GuiInit = null;
    this.stats = null;
    if (this.tween) {
      this.tween.stop();
      this.tween = null;
    }
    cancelAnimationFrame(this.animateFrame);
  };

  private initStats = () => {
    this.stats = new Stats();
    this.stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
    this.stats.dom.style.position = 'absolute';
    this.container.appendChild(this.stats.dom);
  };

  public initGui = () => {
    if (this.GuiInit) {
      this.toggleGui();
      return;
    }
    this.GuiInit = new dat.GUI({
      // autoPlace: false
    });

    this.GuiInit.domElement.style.position = 'absolute';
    this.GuiInit.domElement.style.right = '10px';
    this.GuiInit.domElement.style.top = '10px';

    let GuiController = this.GuiInit.addFolder('控制窗口');
    GuiController.add(this.guiData, 'x', -0.1, 0.1, 0.005).name('自转速度');
    GuiController.addColor(this.guiData, 'color').name('背景颜色');
    GuiController.open();

    // let cubeGui = this.GuiInit.addFolder("cube position");
    // cubeGui.open()
  };

  public toggleGui = (state: any = null) => {
    if (!this.GuiInit || !this.GuiInit.domElement) {
      return;
    }
    let display = this.GuiInit.domElement.style.display == 'none' ? '' : 'none';
    if (state == 0) {
      display = 'none';
    }
    this.GuiInit.domElement.style.display = display;
  };

  private addLight = () => {
    // let ambi = new Three.AmbientLight(0x686868);
    // this.scene.add(ambi);
    // let spotLight = new Three.DirectionalLight(0xffffff);
    // spotLight.position.set(550, 100, 550);
    // spotLight.intensity = 0.6;
    // this.scene.add(spotLight);
    // let light = new Three.PointLight( 0xFFFF00 );
    // light.position.set( -100, 100, 0 );
    // this.scene.add(light);
  };

  private addThings = () => {
    const axesHelper = new Three.AxesHelper(800);
    this.scene.add(axesHelper); //添加坐标轴；红线是X轴，绿线是Y轴，蓝线是Z轴
    this.addParticles();

    this.initTween();
  };

  private radius: number = 0;
  private deltaTimeSeconds = 1 / 60;
  private deltaTimeMilliseconds = this.deltaTimeSeconds * 1000;
  private deltaTimeNormal = this.deltaTimeMilliseconds / (1000 / 60);
  private elapsedMilliseconds: number = 0;
  private addParticles = () => {
    this.particleGroup = new Three.Object3D();
    // this.particleGroup.scale.set(0.0001, 0.0001, 0.0001);
    this.scene.add(this.particleGroup);

    this.Geometrys.sphereGeometry = new Three.SphereBufferGeometry(1, 16, 16);

    let rings = 8;
    this.radius = 0;
    let radiusGrowth = 1.5;

    for (let i = 0; i < rings; i++) {
      let count = i === 0 ? 1 : 1 + Math.ceil(i * 6);

      for (let j = 0; j < count; j++) {
        let angle = (j / count) * Math.PI * 2;
        let x = Math.cos(angle) * this.radius;
        let y = Math.sin(angle) * this.radius;
        let z = 0;
        let size = Calc.map(i, 0, rings, 0.2, 0.05);
        this.particles.push(
          new Particle(
            {
              group: this.particleGroup,
              x: x,
              y: y,
              z: z,
              size: size,
              radius: this.radius,
              angle: angle,
              color: 0xffffff,
              opacity: 1,
            },
            this,
            // this.loader
          ),
        );
      }

      this.radius += radiusGrowth;
    }
  };

  private initTween = () => {
    // var pos: any = { val: 1 };
    // this.tween = new TWEEN.Tween(pos)
    //   .to({ val: 0 }, 1000)
    //   .easing(TWEEN.Easing.Quadratic.InOut)
    //   .delay(200)
    //   .onUpdate(callback);
    // let tweenBack = new TWEEN.Tween(pos)
    //   .to({ val: 1 }, 1000)
    //   .easing(TWEEN.Easing.Quadratic.InOut)
    //   .delay(200)
    //   .onUpdate(callback);
    // this.tween.chain(tweenBack);
    // tweenBack.chain(this.tween);
    // this.tween.start();
    // let that = this;
    // function callback(res) {
    //   that.Materials.starsMaterial.uniforms.val.value = res.val;
    // }
  };

  private timescale: number = 1;
  private clock: any;
  private setupTime = () => {
    this.timescale = 1;
    this.clock = new Three.Clock();
    this.deltaTimeSeconds = this.clock.getDelta() * this.timescale;
    this.deltaTimeMilliseconds = this.deltaTimeSeconds * 1000;
    this.deltaTimeNormal = this.deltaTimeMilliseconds / (1000 / 60);
    this.elapsedMilliseconds = 0;
  };

  private animate = () => {
    // if(!this.renderer){return;}
    if (this.stats) {
      this.stats.begin();
    }

    this.update();
    this.render();

    if (this.stats) {
      this.stats.end();
    }
    this.animateFrame = requestAnimationFrame(this.animate);
  };
  private render = () => {
    this.renderer.setClearColor(this.guiData.color, 1.0);
    // if(this.guiData.autoRotate){
    // }
    this.renderer.render(this.scene, this.camera);
  };
  private update = () => {
    if (1) {
      this.controls.update();
    }
    TWEEN.update();

    let i = this.particles.length;
    while (i--) {
      this.particles[i].update();
    }

    this.deltaTimeSeconds = this.clock.getDelta();
    // if(this.diffTime) {
    // 	this.deltaTimeSeconds -= this.diffTime;
    // 	this.diffTime = 0;
    // }
    this.deltaTimeSeconds *= this.timescale;
    this.deltaTimeMilliseconds = this.deltaTimeSeconds * 1000;
    this.deltaTimeNormal = this.deltaTimeMilliseconds / (1000 / 60);
    this.elapsedMilliseconds += this.deltaTimeMilliseconds;

    // this.system.update();
  };
}

const webGlControl = new WebGlControl();
export default webGlControl;
